package com.zhiwang.planet.ui.entertain

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.chad.library.adapter.base.diff.BaseQuickDiffCallback
import com.pager2banner.IndicatorView
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.databinding.FragmentEntertainV3Binding
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.H5RewardEvent
import com.zhiwang.planet.mvvm.model.entity.main.Banner
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.util.*
import kotlinx.android.synthetic.main.fragment_entertain_v3.*
import kotlinx.android.synthetic.main.h5_rward_alert.*
import kotlinx.android.synthetic.main.h5_rward_alert.view.*
import kotlinx.android.synthetic.main.hint_dialog.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

class EntertainFragmentV3 : BaseFragment() {


    @Inject
    lateinit var viewModel: EntertainV3ViewModel

    lateinit var bannerImageAdapter: BannerImageAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerUserComponent.builder()
                .accountModule(AccountModule(requireActivity() as AppCompatActivity))
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        EventBus.getDefault().register(this)
        viewModel.authView = this
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val binding = DataBindingUtil.inflate<FragmentEntertainV3Binding>(
                inflater,
                R.layout.fragment_entertain_v3,
                container,
                false)

        binding.vm = viewModel
        binding.lifecycleOwner = viewLifecycleOwner
        viewModel.load()
//        if (BuildConfig.DEBUG)
//            viewModel.h5Reward.value = "124782566"
        return binding.root
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel.h5Reward.observe(viewLifecycleOwner, Observer {
            showRewardDialog(it)
        })
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val indicatorView = IndicatorView(context)
                .setIndicatorRatio(1f)
                .setIndicatorRadius(2f)
                .setIndicatorSelectedRatio(3f)
                .setIndicatorSelectedRadius(2f)
                .setIndicatorStyle(IndicatorView.IndicatorStyle.INDICATOR_BIG_CIRCLE)
                .setIndicatorColor(Color.GRAY)
                .setIndicatorSelectorColor(Color.WHITE)

        banner.setAutoPlay(true)
                .setIndicator(indicatorView)
                .setOrientation(ViewPager2.ORIENTATION_HORIZONTAL)
                .setPagerScrollDuration(800)
                .setPageMargin(40.dp, 0) //                .addPageTransformer(new ScaleInTransformer())
                .addPageTransformer(OverlapSliderTransformer(banner.viewPager2.orientation, 0.25f, 0f, 1f, 0f))
                .setOuterPageChangeListener(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {

                    }
                })

        bannerImageAdapter = BannerImageAdapter()
        bannerImageAdapter.setNewDiffData(object : BaseQuickDiffCallback<Banner>(null) {
            override fun areItemsTheSame(oldItem: Banner, newItem: Banner): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: Banner, newItem: Banner): Boolean {
                return oldItem == newItem
            }

        })

        bannerImageAdapter.setOnItemClickListener { adapter, view, position ->
            WebViewActivity.load(requireContext(), (adapter.data[banner.currentPager] as Banner).url)
        }

        banner.adapter = bannerImageAdapter

        viewModel.banner.observe(viewLifecycleOwner, Observer {
            bannerImageAdapter.data.clear()
            bannerImageAdapter.addData(it)
            bannerImageAdapter.notifyDataSetChanged()
        })

//        用 fling 来做合适一点
        recyclerView.layoutManager = object : LinearLayoutManager(requireContext(), HORIZONTAL, false) {

            override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
                val pos = findLastCompletelyVisibleItemPosition()
                if (dx > 0 && pos == recyclerView.adapter!!.itemCount - 1 && overscrolled.not()) {
                    overscrolled = true
                    viewModel.playRecord()
                }
                return super.scrollHorizontallyBy(dx, recycler, state)
            }
        }


        recyclerView1.layoutManager = object : LinearLayoutManager(requireContext(), HORIZONTAL, false) {

            override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
                val pos = findLastCompletelyVisibleItemPosition()
                if (dx > 0 && pos == recyclerView1.adapter!!.itemCount - 1 && overscrolled1.not()) {
                    overscrolled1 = true
                    viewModel.h5Game()
                }
                return super.scrollHorizontallyBy(dx, recycler, state)
            }
        }

    }

    var overscrolled = false

    var overscrolled1 = false


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not())
            viewModel.load()
    }

    override fun onResume() {
        super.onResume()
        viewModel.load()
        overscrolled = false
        overscrolled1 = false
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onH5GameReward(e: H5RewardEvent) {
        viewModel.h5Reward.value = e.reward
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun showRewardDialog(it: String?) {

        if (TextUtils.isEmpty(it) || it == "0") {
            showRewardDialog1()
            return
        }

        val alertRootView = LayoutInflater.from(requireContext()).inflate(R.layout.h5_rward_alert, null)
        val create = AlertDialog.Builder(requireActivity())
                .setView(alertRootView)
                .create()


        val lp = WindowManager.LayoutParams()
        val attributes = create.window?.attributes
        lp.copyFrom(attributes)

        lp.width = (resources.displayMetrics.widthPixels * 0.92).toInt()
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        create.window?.attributes = lp

        alertRootView.continue_gaming.setOnClickListener {

            //继续游戏
            create.dismiss()
            viewModel.h5Game()
        }

        alertRootView.lottery.setOnClickListener {
            create.dismiss()
            WebViewActivity.load(requireContext(), Store.URL_LOTTERY)
        }

        alertRootView.reward.text = it



        create
                .show()

        create.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

    }

    private fun showRewardDialog1() {
        val root = LayoutInflater.from(activity).inflate(R.layout.hint_dialog, null)
        root.msg.text = "累计玩任意一款游戏30分钟，将获得巨额趣豆奖励"
        val create = AlertDialog.Builder(requireActivity())
                .setView(root)
                .create()

        root.positive_btn.text = "继续"
        root.negative_btn.text = "放弃"

        root.positive_btn.setOnClickListener {
            viewModel.loadPrevGame()
            create.dismiss()
        }

        root.negative_btn.setOnClickListener {
            create.dismiss()
        }

        create.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        create.show()
    }


    class OverlapSliderTransformer(
            private val orientation: Int,
            private val minScale: Float = 0f,
            private val unSelectedItemRotation: Float = 0f,
            private val unSelectedItemAlpha: Float = 0f,
            private val itemGap: Float = 0f
    ) : ViewPager2.PageTransformer {

        init {
            require(minScale in 0f..1f) { "minScale value should be between 1.0 to 0.0" }
            require(unSelectedItemAlpha in 0f..1f) { "unSelectedItemAlpha value should be between 1.0 to 0.0" }
        }

        private val scalingValue = 0.2f


        override fun transformPage(page: View, position: Float) {
            page.apply {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    elevation = -kotlin.math.abs(position)
                }

                val delta = (1f - kotlin.math.abs(position * (1 - 0.5f))).coerceAtLeast(0.5f)
                //旋转
                if (unSelectedItemRotation != 0f) {
                    val rotation =
                            (1 - delta) * if (position > 0) unSelectedItemRotation else -unSelectedItemRotation

                    rotationY = rotation
                }

                val scaleDelta = kotlin.math.abs(position * scalingValue)
                val scale = (1f - scaleDelta).coerceAtLeast(minScale)

                scaleX = scale
                scaleY = scale

                when (orientation) {
                    ViewPager2.ORIENTATION_HORIZONTAL -> {
                        translationX =
                                position * (itemGap.toInt() / 2).dp +
                                        if (position > 0) {
                                            (-width * (1f - scale))
                                        } else {
                                            (width * (1f - scale))
                                        }


                        translationY =
                                (height * (1f - scale))

                    }
                    ViewPager2.ORIENTATION_VERTICAL -> {
                        translationY = position * (itemGap.toInt()).dp +
                                if (position > 0) {
                                    (-width * (1f - scale))
                                } else {
                                    (width * (1f - scale))
                                }
                    }
                    else -> throw IllegalArgumentException(
                            "Gives correct orientation value, "
                                    + "ViewPager2.ORIENTATION_HORIZONTAL or ViewPager2.ORIENTATION_VERTICAL")
                }

                if (unSelectedItemAlpha != 1f) {
                    alpha = when {
                        position >= -1f && position <= 1f -> { // (0, 1]
                            // page move from right to center.
                            0.5f + ((1 - kotlin.math.abs(position)) * 0.5f)
                        }
                        else -> {
                            0.5f / kotlin.math.abs(position * position)

                        }
                    }
                }
            }
        }

    }
}